//-----------------------------------------全局变量-------------------------------------------
var numberRegExp = '^[0-9]+$' //纯数字表达式
var letterRegExp = '^[a-zA-Z]+$' //纯字母
var chineseRegExp = '^[\u4e00-\u9fa5]{0,}$' //中文
var emailRegExp = '^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$' //邮箱
var mobileRegExp = '^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$' //手机号码
var idRegExp = '^((d{18})|([0-9x]{18})|([0-9X]{18}))$' //身份证
var ldgDefaultBtns = {
    //默认按钮  移动和删除
    move: {class: 'icon-yidong controlMove'},
    delete: {class: 'icon-shanchu controlDelete'},
}
var contorlCache = []

// 流程定义id
const flowDefId = $.getUrlParam('flowDefId');
// 指定型任务的办理人信息
const assignees = decodeURIComponent($.getUrlParam('assignees'));
//console.log(flowDefId + ";" + assignees);
//-----------------------------------------初始化方法及页面加载方法-------------------------------------------

function GetBtns(btns, id) {
    let str = '<!--表单控件的功能按钮-->'
    str += '<div class="LdgFormItemGroupButton">'
    str += '<span class="LdgFormItemID">' + id + '</span>'
    if (btns) {
        for (let key in btns) {
            str += '<i  class="iconfont ' + btns[key].class + '"></i>'
        }
    } else {
        for (let key in ldgDefaultBtns) {
            str += '<i  class="iconfont ' + ldgDefaultBtns[key].class + '"></i>'
        }
    }
    str += '</div>'
    return str
}

function GetRequired(required) {
    if (required) {
        return '<div class="required">*</div>'
    }
    return ''
}

function GetCheck(required, check = false) {
    if (required || check) {
        return '<div class="errorMain"></div>'
    }
    return ''
}

function getRadioByTextAreaValue(TextAreaValue, optionvalue, id) {
    let spilts = TextAreaValue.split('\n')
    let str = ''
    spilts.forEach(function (item) {
        if (item != '') {
            let checked = ''
            if (item == optionvalue) {
                checked = " checked=''"
            }
            str += `<div class="radio"><label><input type="radio" name="${id}" value="${item}"${checked}>${item}</label></div>`
        }
    })
    return str
}

function getCheckBoxByTextAreaValue(TextAreaValue, optionvalue, id) {
    let spilts = TextAreaValue.split('\n')
    let spiltso = optionvalue.split('\n')
    let str = ''
    spilts.forEach(function (item) {
        if (item != '') {
            let checked = ''
            spiltso.forEach(function (item2) {
                if (item == item2) {
                    checked = " checked=''"
                }
            })
            str += `<div class="checkbox"><label><input  name="${id}" type="checkbox" value="${item}"${checked}>${item}</label></div>`
        }
    })
    return str
}

function getSelectByTextAreaValue(TextAreaValue, optionvalue, id) {
    let spilts = TextAreaValue.split('\n')
    if (!optionvalue || optionvalue.indexOf('请选择') == 0) {
        optionvalue = ''
    }
    let str = `<select name="${id}" class="form-control">`
    spilts.forEach(function (item) {
        let itemvalue = item
        if (itemvalue.indexOf('请选择') == 0) {
            itemvalue = ''
        }
        if (item != '') {
            let selected = ''
            if (itemvalue == optionvalue) {
                selected = " selected=''"
            }
            str += `<option value="${itemvalue}"${selected}>${item}</option>`
        }
    })
    str += '</select>'
    return str
}

function getTextSelectByTextAreaValue(TextAreaValue, id) {
    let spilts = TextAreaValue.split('\n')
    let str = `<input type="text" name="${id}" class="form-control selectInput formVal"><div class="selectInputDiv" title="下拉菜单">`
    spilts.forEach(function (item) {
        if (item != '') {
            str += '<p class="selectInputDivP">' + item + '</p>'
        }
    })
    str += '</div>'
    return str
}

let controlList = {
    //控件英文名
    text: {
        name: '文本框', //控件名称
        icon: 'icon-duohangshurukuang', //控件图标
        datas: {
            //控件属性
            //对象名:{name:"属性名称",value:"默认值",type:"text(文本类型)|number(数字类型)|date(日期型)|datetime(日期型)|select(下拉选择)|radio(单选框)",options(仅支持下拉和单选框):{ 选项1: "值1", 选项2: "值1",选项3:"other(如果值为other,下拉选择支持自定义输入)" }}
            name: {name: '控件名称', value: '文本框', type: 'text'},
            placeholder: {name: '提示语句', value: '', type: 'text'},
            value: {name: '默认内容', value: '', type: 'text'},
            check: {
                name: '校验规则',
                value: '',
                options: {
                    无需校验: '',
                    数字: numberRegExp,
                    字母: letterRegExp,
                    中文: chineseRegExp,
                    邮箱: emailRegExp,
                    手机号: mobileRegExp,
                    身份证: idRegExp,
                    自定义: 'other'
                },
                type: 'select'
            },
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        btns: {
            move: {class: 'icon-yidong controlMove'},
            delete: {class: 'icon-shanchu controlDelete'},
        },
        getHtml: function () {
            return '<input name="' + this.datas.id.value + '" type="text" class="form-control formVal">'
        },
    }, //文本框
    multiple: {
        name: '多行文本框',
        icon: 'icon-danhangshurukuang',
        datas: {
            name: {name: '控件名称', value: '多行文本框', type: 'text'},
            placeholder: {name: '提示语句', value: '', type: 'text'},
            value: {name: '默认内容', value: '', type: 'textarea'},
            height: {name: '控件高度', value: 100, type: 'number'},
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        getHtml: function () {
            return '<textarea name="' + this.datas.id.value + '" class="form-control formVal" cols="30" rows="5" style="resize: none;"></textarea>'
        },
    }, //多行文本框
    date: {
        name: '日期选择框',
        icon: 'icon-riqixuanzeqi',
        datas: {
            name: {name: '控件名称', value: '日期框', type: 'text'},
            value: {name: '默认内容', value: '', type: 'date'},
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        getHtml: function () {
            return '<input name="' + this.datas.id.value + '" type="date" class="form-control formVal">'
        },
    }, //日期选择框
    datetime: {
        name: '时间选择框',
        icon: 'icon-shijianxuanzeqi',
        datas: {
            name: {name: '控件名称', value: '时间框', type: 'text'},
            value: {name: '默认内容', value: '', type: 'datetime-local'},
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        getHtml: function () {
            return '<input name="' + this.datas.id.value + '" type="datetime-local" class="form-control formVal">'
        },
    }, //时间选择框
    radio: {
        name: '单选框',
        icon: 'icon-danxuan',
        datas: {
            name: {name: '控件名称', value: '单选框', type: 'text'},
            value: {name: '默认勾选', value: '选项一', type: 'text'},
            options: {name: '单选框选项（一行一个选项）', value: '选项一\n选项二', type: 'textarea'},
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        getHtml: function () {
            return getRadioByTextAreaValue(this.datas.options.value, this.datas.value.value, this.datas.id.value)
        },
    }, //单选框
    checkbox: {
        name: '多选框',
        icon: 'icon-duoxuan',
        datas: {
            name: {name: '控件名称', value: '多选框', type: 'text'},
            value: {name: '默认勾选', value: '多选一\n多选二', type: 'textarea'},
            options: {name: '多选框选项（一行一个选项）', value: '多选一\n多选二\n多选三', type: 'textarea'},
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        getHtml: function () {
            return getCheckBoxByTextAreaValue(this.datas.options.value, this.datas.value.value, this.datas.id.value)
        },
    }, //多选框
    dropdown: {
        name: '下拉选择框',
        icon: 'icon-choose1',
        datas: {
            name: {name: '控件名称', value: '下拉选择框', type: 'text'},
            value: {name: '默认选择', value: '请选择省份', type: 'text'},
            options: {name: '下拉框选项（一行一个选项）', value: '请选择省份\n河南\n河北\n山东', type: 'textarea'},
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        getHtml: function () {
            return getSelectByTextAreaValue(this.datas.options.value, this.datas.value.value, this.datas.id.value)
        },
    }, //下拉选择框
    textdropdown: {
        name: '文本下拉框',
        icon: 'icon-xialaxuanze',
        datas: {
            name: {name: '控件名称', value: '文本下拉框', type: 'text'},
            value: {name: '默认内容', value: '', type: 'text'},
            placeholder: {name: '提示语句', value: '', type: 'text'},
            options: {name: '下拉框选项（一行一个选项）', value: '操作证一级\n操作证二级\n电工操作证', type: 'textarea'},
            required: {name: '是否必填', value: 0, options: {必填: 0, 选填: 1}, type: 'radio'},
        },
        getHtml: function () {
            return getTextSelectByTextAreaValue(this.datas.options.value, this.datas.value.value, this.datas.id.value)
        },
    }, //文本下拉框
    //img: { name: '图片上传', icon: 'icon-ic_image_upload' }, //图片上传
    //file: { name: '文件上传', icon: 'icon-wenjianshangchuan' }, //文件上传
}

//图片
function getImg() {
    //<!--具体的表单控件 图片-->
    var str = '<div class="row"><div class="LdgFormItem" data-type="img" data-choice="true" data-num="1" >'
    //<!--表单控件的头部-->
    str += '<div class="LdgFormItemHead">'
    //<!--表单控件的名称-->
    str += '<div class="required">*</div><div class="LdgFormItemName">上传图片</div>'
    //<!--表单控件的功能按钮-->
    str += '<div class="LdgFormItemGroupButton">'
    str += '<button type="button" class="btn btn-primary controlMove">移动</button>'
    str += '<button type="button" class="btn btn-primary controlDelete">删除</button>'
    str += '</div></div>'
    //<!--控件-->
    str += '<div class="LdgFormItemContent">'
    str += '<div class="form-group hidMargin">'
    str += '<div class="img-box full">'
    str += '<section class="img-section">'
    str += '<div class="z_photo upimg-div clear">'
    str += '<section class="z_file fl">'
    str += '<div class="z_fileImgDel">删除</div>'
    str += '<img src="../images/a11.png" class="add-img" />'
    str += '<input type="file" name="file" class="file imgFile" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" leipiplugins="imgupload" title="图片上传" />'
    str += '</section></div></section>'
    str += '<div class="imgExplain">支持jpg、jpeg、png、bmp等图片格式</div>'
    str += '<div class="errerClass imgErrer"></div>'
    str += '</div>'
    str += '</div><div class="errorMain"></div></div></div></div>'
    return str
}

//文件
function getFile() {
    //<!--具体的表单控件 图片-->
    var str = '<div class="row"><div class="LdgFormItem" data-type="file" data-choice="true" data-num="1" >'
    //<!--表单控件的头部-->
    str += '<div class="LdgFormItemHead">'
    //<!--表单控件的名称-->
    str += '<div class="required">*</div><div class="LdgFormItemName">上传文件</div>'
    //<!--表单控件的功能按钮-->
    str += '<div class="LdgFormItemGroupButton">'
    str += '<button type="button" class="btn btn-primary controlMove">移动</button>'
    str += '<button type="button" class="btn btn-primary controlDelete">删除</button>'
    str += '</div></div>'
    //<!--控件-->
    str += '<div class="LdgFormItemContent">'
    str += '<div class="form-group hidMargin">'
    str += '<div class="message">'
    str += '<div class="messagedel">删除</div>'
    str += '<input type="text" name="txt" class="input fileUpload form-control" value="" disabled="disabled" />'
    str += '<input type="button" value="上传文件" size="30" class="liulan fileUploadBtn">'
    str += '<input type="file" name="f" style="height:26px;" class="files leipiplugins fileUploadReal" size="1" leipiplugins="uploadfile" title="文件上传" hidefocus></div>'
    str += '<div class="fileTips">'
    str += '<p>1.上传文档不超过100MB</p>'
    str += '<p>2.为了保证文档能正常使用，我们支持以下格式的文档上传：</p>'
    str += '<p>MS Office文档： doc,docx,ppt,pptx,xls,xlsx,vsd,pot,pps,rtf</p>'
    str += '<p>压缩文档： rar,zip,tar,gz,tgz</p>'
    str += '<p>图片： jpg,jpeg,gif,bmp,png</p>'
    str += '<p>WPS office系列： wps,et,dps</p>'
    str += '<p>PDF： pdf</p>'
    str += '<p>纯文本： txt</p>'
    str += '<p>EPUB： epub</p></div>'
    str += '<div class="errerClass FileErrer"></div>'
    str += '</div><div class="errorMain"></div></div></div></div>'
    return str
}

function switchType(typeinfo, type, isdiy) {
    if ('undefined' != typeof typeinfo.getDiyHtml) {
        return typeinfo.getDiyHtml(isdiy)
    }
    if ('undefined' != typeof typeinfo.getHtml) {
        let html = '<div class="row"><div class="LdgFormItem" data-id="' + typeinfo.datas.id.value + '" data-type="' + type + '">' + '<div class="LdgFormItemHead"><div class="LdgFormItemName">' + GetRequired(typeinfo.datas.required) + '<span>' + typeinfo.datas.name.value + '</span>' + '</div></div>';
        if (isdiy) {
            html += GetBtns(typeinfo.btns, typeinfo.datas.id.value)
        }
        html += '<div class="LdgFormItemContent"><div class="form-group hidMargin">' + typeinfo.getHtml(isdiy) + '</div>' + GetCheck(typeinfo.datas.required, typeinfo.datas.check) + '</div>'
        return html
    }
    var str
    switch (type) {
        case 'img':
            str = getImg()
            break
        case 'file':
            str = getFile()
            break
        default:
            str = ''
            break
    }
    return str
}

function addControl(type, typeinfo = null, previewel = "") {

    let typec = controlList[type].deepClone()

    typec.datas['id'] = {name: '控件标识', value: type + '_' + Math.round(new Date().getTime()), type: 'text'}
    if (typeinfo != null) {
        for (let key in typeinfo) {
            typec.datas[key].value = typeinfo[key]
        }
    }
    let isdiyform = false
    if (previewel == "") {
        previewel = '.LdgFormSubjectForm';
        isdiyform = true
    }

    typec['type'] = type
    var str = switchType(typec, type, isdiyform)

    //获取当前中部控件，删除放置效果及处理单选框多选框name相同的问题
    var item = $(previewel).find('.row')

    if (item.length > 0) {
        //判断是否位置放好了，有时候没有放置在控件上，就放置到最底层
        var isSelectPosition = false
        for (var i = 0; i < item.length; i++) {
            if (item.eq(i).hasClass('placeLocationBottom')) {
                if (isdiyform) {
                    contorlCache.splice(i + 1, 0, typec)
                }
                item.eq(i).after(str)
                object = $(item.eq(i)).next()
                item.eq(i).removeClass('placeLocationBottom')
                isSelectPosition = true
            } else if (item.eq(i).hasClass('placeLocationTop')) {
                if (isdiyform) {
                    contorlCache.splice(i, 0, typec)
                }
                item.eq(i).before(str)
                object = $(item.eq(i)).prev()
                item.eq(i).removeClass('placeLocationTop')
                isSelectPosition = true
            }
        }
        if (!isSelectPosition) {
            object = $(str).appendTo(previewel)
            if (isdiyform) {
                contorlCache.push(typec)
            }
        }
    } else {
        object = $(str).appendTo(previewel)
        if (isdiyform) {
            contorlCache.push(typec)
        }
    }
    object = $(object).find(".LdgFormItem")
    if (typeinfo != null) {
        ChangeControl('id', typeinfo['id'], 'text')
        for (let key in typeinfo) {
            ChangeControl(key, typeinfo[key], type, typec.datas)
        }
    }
}

function ChangeControl(AttrKey, AttrValue, AttrType, datas) {
    if (AttrKey == 'name') {
        object.find('.LdgFormItemName span').text(AttrValue)
    } else if (AttrKey == 'options' || AttrKey == 'value') {
        let tempid = object.data('id')
        let tempoption = AttrValue
        // if (!tempoption) {
        // 	tempoption = objectControl.datas['value'].value
        // }
        let temphtml = '未知的类型'
        let upval = false
        if (AttrType.indexOf('radio') == 0) {
            temphtml = getRadioByTextAreaValue(datas.options.value, datas.value.value, tempid)
        } else if (AttrType.indexOf('checkbox') == 0) {
            temphtml = getCheckBoxByTextAreaValue(datas.options.value, datas.value.value, tempid)
        } else if (AttrType.indexOf('dropdown') == 0) {
            temphtml = getSelectByTextAreaValue(datas.options.value, datas.value.value, tempid)
        } else if (AttrType.indexOf('textdropdown') == 0) {
            temphtml = getTextSelectByTextAreaValue(datas.options.value, datas.value.value, tempid)
        } else {
            upval = true
        }
        if (upval) {
            object.find('.formVal').val(AttrValue)
        } else {
            object.find('.form-group').html(temphtml)
        }

    } else if (AttrKey == 'id') {
        object.find('.LdgFormItemID').text(AttrValue)
        object.data('id', AttrValue)
    } else if (AttrKey == 'placeholder') {
        object.find('.formVal').attr('placeholder', AttrValue)
    } else if (AttrKey == 'height') {
        object.find('.formVal').height(AttrValue)
    } else if (AttrKey == 'required') {
        if (AttrValue == '0') {
            object.find('.required').removeClass('requiredHiddle')
        } else {
            object.find('.required').addClass('requiredHiddle')
        }
    } else if (AttrKey == 'check') {
        object.data("check", AttrValue)
    } else {
        //未知的参数不要处理,否则都会录入到内容中
        //object.find('.formVal').val(AttrValue)
    }
}

/**
 * 导入json
 */
function ImportJson(json, showel = "") {
    try {
        let cd = JSON.parse(json)
        cd.list.forEach((c) => {
            addControl(c.type, c.options, showel)
        })

    } catch (err) {
        toastr.error('导入错误,请检查导入数据是否正确')
        console.log(err)
    }
}

function GetForm(showel, preview = false) {
    let formdata = $(showel).serializeArray();
    let json = new Object()
    formdata.forEach((c) => {
        var name = c.name;
        var value = c.value;
        if (name.indexOf('checkbox_') != -1) {
            var array = json[name];
            if (array == null) {
                array = [];
            }
            array.push(value);
            json[name] = array
        } else {
            json[name] = value;
        }
    })
    if (preview) {
        return JSON.stringify(json, null, '\t')
    }
    return JSON.stringify(json)
}

//JS对象深度克隆
const deepClone = function (obj) {
    // 先检测是不是数组和Object
    // let isArr = Object.prototype.toString.call(obj) === '[object Array]';
    let isArr = Array.isArray(obj)
    let isJson = Object.prototype.toString.call(obj) === '[object Object]'
    if (isArr) {
        // 克隆数组
        let newObj = []
        for (let i = 0; i < obj.length; i++) {
            newObj[i] = deepClone(obj[i])
        }
        return newObj
    } else if (isJson) {
        // 克隆Object
        let newObj = {}
        for (let i in obj) {
            newObj[i] = deepClone(obj[i])
        }
        return newObj
    }
    // 不是引用类型直接返回
    return obj
}

Object.prototype.deepClone = function () {
    return deepClone(this)
}
Object.defineProperty(Object.prototype, 'deepClone', {enumerable: false})

$(function () {
    //读取表单数据
    getForm();

    //监听选择文件事件
    $('#fileupload').change(function () {
        let files = $(this).prop('files');
        for (let i = 0; i < files.length; i++) {
            let file = files[i];
            let fileName = file.name;
            if (fileName.indexOf(".") === -1) {
                toastr.warning('禁止上传没有扩展名的附件');
                continue;
            }
            let $previewItem = $(  '<div class="preview-item">' +
                    '<span class="pull-left">'+ file.name +'</span>' +
                    '<a class="pull-right" href="javascript:void(0);">删除</a>\n' +
                '</div>');
            $previewItem.data('file', file);
            $previewItem.find('a').click(function () {
                $(this).parent().remove();
            });
            $('.preview').append($previewItem);
        }
    });

    $('#submit').click(function () {
        //提交表单
        submitForm();
    });

})

/**
 * 上传文件
 */
function uploadFile(flowInstId, msg) {
    //获取文件对象
    let fileList = [];
    $('.preview-item').each(function (index, e) {
        let file = $(this).data('file');
        fileList.push(file);
    });

    if (fileList.length > 0) {
        //有附件
        //初始化
        $('#fileupload').fileupload();
        $('#fileupload').fileupload('send',
            {
                files: fileList,
                url: '/attach/upload',
                sequentialUploads: true,
                formData: {flowInstId: flowInstId}
            })
            .success(function (data, textStatus, jqXHR) {
                // console.log(data)
                // console.log(textStatus)
                // console.log(jqXHR)
                if (data.code === SUCCESS_CODE) {
                    //成功
                    toastr.success(msg);
                    // 跳转到“我的申请”列表
                    setTimeout(function () {
                        goto("/admin/flowinst/start_flow_list.html");
                    }, 2000);
                } else {
                    toastr.error(msg + ';' + data.msg);
                }
            })
            .error(function (jqXHR, textStatus, errorThrown) {
                //遇到错误
                toastr.error(msg + ';上传附件失败');
            })
            .complete(function (result, textStatus, jqXHR) {
                //完成，相当于finally
                //console.log('complete');
            });
        //销毁
        $('#fileupload').fileupload('destroy');
    } else {
        //没有附件
        toastr.success(msg);
        // 跳转到“我的申请”列表
        setTimeout(function () {
            goto("/admin/flowinst/start_flow_list.html");
        }, 2000);
    }

}

/**
 * 提交表单
 */
function submitForm() {
    let showel = "#flowDefForm"
    if (CheckForm(showel)) {
        $("#ldgFormPreview").modal("hide");
        let json = GetForm(showel, true);
        let startFlowDto = new Object();
        startFlowDto.flowDefId = flowDefId;
        startFlowDto.flowFormData = json;
        startFlowDto.assignees = JSON.parse(assignees);
        //console.log(startFlowDto);

        $.ajax({
            type: "POST",
            url: "/flowInst/startFlow",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(startFlowDto),
            success: function (data) {
                if (data.code === SUCCESS_CODE) {
                    let flowInstId = data.payload;
                    uploadFile(flowInstId, data.msg);
                } else {
                    toastr.error(data.msg);
                }
            }
        });
    }
}


/**
 * 回显表单
 */
function getForm() {

    $.ajax({
        type: "GET",
        url: "/flowDefForm/getById",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: {"flowDefId": flowDefId},
        success: function (data) {
            if (data.code === SUCCESS_CODE) {
                if (!$.isEmptyObject(data.payload) && !$.isEmptyObject(data.payload.structure)) {
                    let showel = "#flowDefForm"
                    $(showel).empty()
                    if (!$(showel).hasClass("LdgFormSubjectForm")) {
                        $(showel).addClass("LdgFormSubjectForm");
                    }
                    ImportJson(data.payload.structure, showel);
                }
            } else {
                toastr.error(data.msg);
            }
        }
    });
}

//--------

function CheckForm(showel) {
    let checkForm = true;
    var Items = $(showel).find(".LdgFormItem");
    for (var i = 0; i < Items.length; i++) {
        var item = Items.eq(i);
        let bool = isChoice(item);//判断该控件是否需要填写
        if (!bool) {
            checkForm = false
        }
        if (item.data("type") == "text") {
            if (bool) {
                if (!textRegExp(item)) {
                    checkForm = false
                }
            } else {
                checkForm = false
            }
        }
    }
    return checkForm
}

//文本框正则表达式
function textRegExp(object) {
    var limit = object.data("check");//正则表达式
    if (limit != null && limit != "") {
        var val = object.find(".formVal").val();//文本框的值
        var bool = new RegExp(limit).test(val);
        if (bool) {
            object.find(".errorMain").hide();
            return true;
        } else {
            if (val == "") {
                object.find(".errorMain").hide();
                return true;
            } else {
                object.find(".errorMain").text("请输入正确格式的数据").show();
                return false;
            }
        }
    }
    return true
}


//选项是否必填
function isChoice(object) {
    var choice = $(object).find(".required").is(':visible')
    if (choice) {
        let type = object.data("type")
        if (type == "text" || type == "multiple" || type == "date" || type == "datetime") {
            var val = object.find(".formVal").val();
            ;//获取值，可用于文本框、多行文本框、时间框
            var bool = TextMultipleDateValIsNull(val);//判断string是否为空，不为空为真
            showChoiceErrorInfo(object, bool);//显示必填的错误信息
            return bool;
        } else if (type == "radio" || type == "checkbox") {
            var val = getRadioCheckboxVal(object);//获取单选按钮、多选按钮的值
            var bool = TextMultipleDateValIsNull(val);//判断string是否为空，不为空为真
            showChoiceErrorInfo(object, bool);//显示必填的错误信息
            return bool;
        } else if (type == "dropdown") {
            //下拉框有默认值
            return true;
        } else if (type == "textdropdown") {
            var val = getTextdropdownVal(object);//获取单选按钮、多选按钮的值
            var bool = TextMultipleDateValIsNull(val);//判断string是否为空，不为空为真
            showChoiceErrorInfo(object, bool);//显示必填的错误信息
            return bool;
        } else if (type == "img" || type == "file") {
            var bool = isImgFileValNull(object);
            showChoiceErrorInfo(object, bool);//显示必填的错误信息
            return bool;
        }
    }
    return true;
}

//判断文本框、多行文本框、时间框的值是否为空，可用于判断字符串的值
function TextMultipleDateValIsNull(val) {
    if (val != null && val != "") {
        return true;
    } else {
        return false;
    }
}

//显示必填的错误信息
function showChoiceErrorInfo(object, bool) {
    if (bool) {
        object.find(".errorMain").hide();
    } else {
        object.find(".errorMain").text("此项为必填项，请填写！").show();
    }
}


//获取单选按钮、多选按钮的值
function getRadioCheckboxVal(object) {
    var val = "";
    var inputs = object.find("input");
    for (var i = 0; i < inputs.length; i++) {
        var checked = inputs.eq(i).prop("checked");
        if (checked) {
            val += inputs.eq(i).val() + "\n";
        }
    }
    if (val.indexOf("\n") > -1) {
        val = val.substring(0, val.length - 1);
    }
    return val;
}